package com.gene.controller.user;

import com.gene.pojo.UpmsRole;
import com.gene.pojo.UpmsUser;
import com.gene.request.userRegisterRequest;
import com.gene.service.IUpmsUserService;
import com.gene.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
@RequestMapping("gene-safe")
public class UpmsUsercontroller {

    @Autowired
    private IUpmsUserService upmsUserService;

    @Autowired
    private RedisTemplate<String, String> template;

    /**
     * 登陆
     *
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/upmsUser/login",produces ="application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public ResultData login(@RequestParam(value = "userName",defaultValue = "1", required = true)String userName,@RequestParam(value = "password",defaultValue = "1", required = true)String password, HttpServletRequest request,HttpServletResponse response) throws Exception {
        ResultData result = new ResultData();
        if (userName.equals("1") || password.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PARAMETERS_ISNULL);
            return result;
        }
        UpmsUser user = upmsUserService.selectUserNameAndPassword(userName, password);
        if (null == user) {
            result.setErrorCode(CodeValue.USER_USERNAME_ISNULL);
            result.setMsg(MsgValue.USER_USERNAME_ISNULL);
            return result;
        }
        boolean verify = MD5Util.verify(password, user.getPassword());
        if (!verify) {
            //不一致
            result.setErrorCode(CodeValue.USER_PASSWORD_ISNULL);
            result.setMsg(MsgValue.USER_PASSWORD_ISNULL);
            return result;
        }else {
            // 记住用户名:
            String remember = request.getParameter("remember");
            if("true".equals(remember)){
                Cookie cookie = new Cookie("username",user.getUsername());
                cookie.setPath("/gene-safe");
                cookie.setMaxAge(24 * 60 * 60);
                response.addCookie(cookie);
            }
            List<UpmsRole> roles = upmsUserService.selectUserRole(user.getUserId());
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            Map<String, Object> map = new HashMap<>();
            user.setPassword(null);
            map.put("user", user);//用户信息
            map.put("roles", roles);//用户拥有的角色信息

            if(null!=template.opsForValue().get(user.getUserId()+user.getUsername())){
                template.delete(user.getUserId()+user.getUsername());
            }
            String token = JWT.sign(user, 24L*60L* 60L*1000L);
            System.out.println(token);
            map.put("token",token);
            result.setData(map);
            HttpSession session = request.getSession();
            //设定SESSION不操作情况下失效时间（单位毫秒）
            session.setMaxInactiveInterval(30 * 60);
            session.setAttribute(Const.SESSION_USERROL, roles);//存入角色
            session.setAttribute(Const.SESSION_USER, user);//存入用户信息
            template.opsForValue().set(user.getUserId()+user.getUsername(),token,60 * 60 * 24, TimeUnit.SECONDS);
            return result;
        }

    }

    /*
         注册
        */
    @RequestMapping(value = "/upmsUser/register", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData register(userRegisterRequest user, @RequestParam(value = "codes",defaultValue = "1") String code) {
        ResultData result = new ResultData();
        UpmsUser toUser = upmsUserService.selectUserNameAndPassword(user.getUserName(), user.getPassWord());
        if (null != toUser) {
            result.setErrorCode(CodeValue.USER_EXISTENCE);
            result.setMsg(MsgValue.USER_EXISTENCE);
            return result;
        }
        String get = template.opsForValue().get(user.getPhone());
        System.out.println(get+"验证码");
        if (get == null || !get.equals(code)) {
            //验证码无效
            result.setErrorCode(CodeValue.USER_CODE_ISNULL);
            result.setMsg(MsgValue.USER_CODE_ISNULL);
            return result;
        }
        int i = upmsUserService.insertUser(user);
        if (i != 1) {
            result.setErrorCode(CodeValue.USER_REGISTER_FAIL);
            result.setMsg(MsgValue.USER_REGISTER_FAIL);
            return result;
        }
        template.delete(user.getPhone());
        result.setErrorCode(CodeValue.SUCCESS);
        result.setMsg(MsgValue.SUCCESS);
        return result;
    }

    /*
        发短信
     */
    @RequestMapping(value = "/upmsUser/sms", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData sms(@RequestParam(defaultValue = "1") String phone) throws Exception {
        ResultData result = new ResultData();
        if (phone.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PARAMETERS_ISNULL);
            return result;
        }
        Integer randomCode = (int) ((Math.random() * 9 + 1) * 100000);
        SmsUtils.sendSmsByHTTP(phone, "尊敬的用户您好，本次获取的验证码为：" + randomCode + "【喔巢app】");
        if(null!=template.opsForValue().get(phone)){
            template.delete(phone);
        }
        template.opsForValue().set(phone, randomCode + "", 60 * 5, TimeUnit.SECONDS);
        result.setErrorCode(CodeValue.SUCCESS);
        result.setMsg(MsgValue.SUCCESS);
        return result;
    }

    /*
       验证手机号
        */
    @RequestMapping(value = "/upmsUser/phone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData phone(@RequestParam(defaultValue = "1") String phone) throws Exception {
        ResultData result = new ResultData();
        if (phone.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PHONE_NULL);
            return result;
        }

        //正则判断手机号码格式正确
        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-9]|17[1456789]|18[0-9])\\d{8}$");
        Matcher m = p.matcher(phone);
        boolean b=m.matches();
        if(!b){//不匹配
            result.setErrorCode(CodeValue.USER_PHONE);
            result.setMsg(MsgValue.USER_PHONE);
            return result;
        }

        UpmsUser user = upmsUserService.selectUserPhone(phone);
        if (null != user) {
            result.setErrorCode(CodeValue.USER_PHONE_EXISTENCE);
            result.setMsg(MsgValue.USER_PHONE_EXISTENCE);
            return result;
        }
        result.setErrorCode(CodeValue.SUCCESS);
        result.setMsg(MsgValue.CORRECT);
        return result;
    }

    /*
    验证用户名
     */
    @RequestMapping(value = "/upmsUser/userName", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData idcar(@RequestParam(defaultValue = "1") String userName) throws Exception {
        ResultData result = new ResultData();
        if (userName.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_NAME_NULL);
            return result;
        }
        UpmsUser user = upmsUserService.selectUserNameAndPassword(userName, "1");
        if (null == user) {
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.CORRECT);
            return result;
        }

        result.setErrorCode(CodeValue.USER_EXISTENCE);
        result.setMsg(MsgValue.USER_EXISTENCE);
        return result;

    }


    /*
     找回密码   验证手机号
      */
    @RequestMapping(value = "/upmsUser/BackPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData BackPhone(@RequestParam(defaultValue = "1") String phone) throws Exception {
        ResultData result = new ResultData();
        if (phone.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PHONE_NULL);
            return result;
        }

        //正则判断手机号码格式正确
        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-9]|17[1456789]|18[0-9])\\d{8}$");
        Matcher m = p.matcher(phone);
        boolean b=m.matches();
        if(!b){//不匹配
            result.setErrorCode(CodeValue.USER_PHONE);
            result.setMsg(MsgValue.USER_PHONE);
            return result;
        }

        UpmsUser user = upmsUserService.selectUserPhone(phone);
        if (null != user) {
            result.setData(user);
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            return result;
        }
        result.setErrorCode(CodeValue.USER_PHONE_GIT);
        result.setMsg(MsgValue.USER_PHONE_GIT);
        return result;
    }



    /*
       找回密码发短信
    */
    @RequestMapping(value = "/upmsUser/BackSms", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData BackSms(@RequestParam(defaultValue = "1") Integer userId) throws Exception {
        ResultData result = new ResultData();
        if (userId.intValue() == 1) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PARAMETERS_ISNULL);
            return result;
        }
        UpmsUser user = upmsUserService.selectuserID(userId);
        if(null==user){
            result.setErrorCode(CodeValue.ENTITY_ISNULL);
            result.setMsg(MsgValue.ENTITY_ISNULL("UpmsUser"));
            return result;
        }
        Integer randomCode = (int) ((Math.random() * 9 + 1) * 100000);
        SmsUtils.sendSmsByHTTP(user.getPhone(), "尊敬的用户您好，本次获取的验证码为：" + randomCode + "【喔巢app】");
        template.opsForValue().set(user.getUserId()+user.getPhone(), randomCode + "", 60 * 5, TimeUnit.SECONDS);
        result.setErrorCode(CodeValue.SUCCESS);
        result.setMsg(MsgValue.SUCCESS);
        return result;
    }
    /*
    找回密码
    验证验证码是否过期
     */
    @RequestMapping(value = "/upmsUser/Back", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData Back(@RequestParam(defaultValue = "1") Integer userId,@RequestParam(defaultValue = "1")String code) throws Exception {
        ResultData result = new ResultData();
        if (userId.intValue() == 1||code.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PARAMETERS_ISNULL);
            return result;
        }
        UpmsUser user = upmsUserService.selectuserID(userId);
        if(null==user){
            result.setErrorCode(CodeValue.ENTITY_ISNULL);
            result.setMsg(MsgValue.ENTITY_ISNULL("UpmsUser"));
            return result;
        }
        String s = template.opsForValue().get(user.getUserId() + user.getPhone());
        if(s!=null&&s.equals(code)){
            template.delete(user.getUserId() + user.getPhone());
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.CORREC);
            return result;
        }
        result.setErrorCode(CodeValue.USER_CODE_ISNULL);
        result.setMsg(MsgValue.USER_CODE_ISNULL);
        return result;
    }

    /**
     * 用户设置新密码
     */
    @RequestMapping(value = "/upmsUser/BackPass", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData BackPass(@RequestParam(defaultValue = "1") Integer userId,@RequestParam(defaultValue = "1")String password) throws Exception {
        ResultData result = new ResultData();
        if (userId.intValue() == 1||password.equals("1")) {
            result.setErrorCode(CodeValue.USER_PARAMETERS_ISNULL);
            result.setMsg(MsgValue.USER_PARAMETERS_ISNULL);
            return result;
        }
        UpmsUser user = upmsUserService.selectuserID(userId);
        if(null==user){
            result.setErrorCode(CodeValue.ENTITY_ISNULL);
            result.setMsg(MsgValue.ENTITY_ISNULL("UpmsUser"));
            return result;
        }
        String generate = MD5Util.generate(password);
        user.setPassword(generate);
        int i = upmsUserService.updetePassword(user);
        if(i==1){
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            return result;
        }
        result.setErrorCode(CodeValue.USER_PASSWORD_FAIL);
        result.setMsg(MsgValue.USER_PASSWORD_FAIL);
        String token = JWT.sign(user, 60L * 30L * 1000L);
        template.delete(user.getUserId()+user.getUsername());
        template.opsForValue().set(user.getUserId()+user.getUsername(),token,60 * 30, TimeUnit.SECONDS);
        result.setData(token);
        return result;
    }

    /**
     * 用户退出功能的方法:logOut
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upmsUser/logOut", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData logOut(HttpServletRequest req,HttpServletResponse resp,UpmsUser user){
        try {
            ResultData result = new ResultData();
            // 销毁session
            req.getSession().invalidate();
            // 清空自动登录的Cookie:
            Cookie cookie = new Cookie("autoLogin","");
            cookie.setPath("/gene-sefa");
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
            template.delete(user.getUserId()+user.getUsername());
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("服务器繁忙");
        }
    }

    /**
     * 刷新token的方法
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/Refresh", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultData Refresh(HttpServletRequest req,HttpServletResponse resp,UpmsUser upmsUser){
        try {
            ResultData result = new ResultData();
            String authorization = req.getHeader("Authorization");//获取token
            String s = template.opsForValue().get(upmsUser.getUserId() + upmsUser.getUsername());
            if(authorization.equals(s)){
                String sign = JWT.sign(upmsUser, 60 * 30 * 1000);
                template.delete(upmsUser.getUserId()+upmsUser.getUsername());
                template.opsForValue().set(upmsUser.getUserId()+upmsUser.getUsername(),sign,60 * 30, TimeUnit.SECONDS);
                result.setData(sign);
                result.setErrorCode(CodeValue.SUCCESS);
                result.setMsg(MsgValue.SUCCESS);
                return result;
            }
            result.setErrorCode(CodeValue.TOKEN_ISNULL);
            result.setMsg(MsgValue.TOKEN_ISNULL);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("服务器繁忙");
        }
    }

}
